package cn.dakaqi.api.qnzyz.activity;

import cn.dakaqi.api.qnzyz.pojo.BHActivity;
import cn.dakaqi.api.qnzyz.pojo.BHRecord;
import cn.dakaqi.api.qnzyz.util.BHAccesssToken;
import cn.dakaqi.api.qnzyz.util.BHConstant;
import cn.dakaqi.entities.Activity;
import cn.dakaqi.utils.DKQConstant;
import cn.dakaqi.utils.http.HttpsUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.ValueFilter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Authoer:chunyang
 * ProjectName:Volunteer
 * Date: 2015/7/14.
 * Description:
 */
@Component
public class BHActivityService
{
    @Autowired
    BHAccesssToken bhAccesssToken;
    static String pageSize = "20";
    private ValueFilter filter = new ValueFilter() {
        @Override
        public Object process(Object obj, String s, Object v) {
            if(v==null)
                return "";
            return v;
        }
    };
    private static SerializerFeature[] features = {SerializerFeature.WriteNullNumberAsZero, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.DisableCircularReferenceDetect};


    /**
     * 活动发布
     * 第三方平台发布项目活动后通过该接口把数据同步到志愿者管理信息平台
     * @param activity
     * @return
     */
    public String post(Activity activity)throws Exception
    {
            String activityCode = null;
            BHActivity bhActivity = BHActivity.nativeact2bhact(activity);
            String postUrl = BHConstant.checkNetWork()+"/api/v1/activity/post?client="+ BHConstant.CLIENTID
                    + "&token=" + bhAccesssToken.getAccessToken(BHConstant.CLIENTID);
            String postEntity =  JSON.toJSONString(bhActivity,filter);
            JSONObject jsonOb = JSON.parseObject(postEntity);
            jsonOb.remove("activityCode");
            jsonOb.remove("groupName");
            jsonOb.remove("activityScore");

            postEntity = jsonOb.toJSONString();

            String result = HttpsUtil.post(postUrl, postEntity);
            if(result != null && !result.trim().equals(""))
            {
                JSONObject jsonObject = JSON.parseObject(result);
                if (jsonObject != null)
                {
                    int res_code = jsonObject.getInteger("ret");
                    String msg = jsonObject.getString("msg");
                    if (res_code == 0)
                    {
                        activityCode = jsonObject.getJSONObject("result").getString("activityCode");
                    } else if (res_code == BHConstant.TOKEN_TIMEOUT)
                    {
                        bhAccesssToken.refreshToken(BHConstant.CLIENTID);
                        //post(DKQConstant.CLIENTID, activity);
                        throw new Exception(msg);
                    } else
                    {
                        throw new Exception(msg);
                    }

                }
            }
            return activityCode;
    }

    /**
     * 活动信息更新
     * 第三方平台发布项目活动信息更新后通过该接口把数据同步到志愿者管理信息平台
     * 
     * @param activity
     * @return
     */
    public int update(Activity activity)throws Exception
    {
        int ret = 100;
            BHActivity bhActivity = BHActivity.nativeact2bhact(activity);
            bhActivity.setActivityCode(activity.getActivityCode());

            System.out.println(bhActivity);
            String postUrl = BHConstant.checkNetWork()+"/api/v1/activity/update?client="+ BHConstant.CLIENTID
                    + "&token=" + bhAccesssToken.getAccessToken(BHConstant.CLIENTID);
            String postEntity = JSON.toJSONString(bhActivity,filter);

            JSONObject jsonOb = JSON.parseObject(postEntity);
            jsonOb.remove("groupCode");
            jsonOb.remove("groupName");
            jsonOb.remove("activityScore");
            postEntity = jsonOb.toJSONString();


            String result = HttpsUtil.post(postUrl, postEntity);
            if(result != null && !result.trim().equals(""))
            {
                JSONObject jsonObject = JSON.parseObject(result);
                if(jsonObject != null)
                {
                    ret = jsonObject.getInteger("ret");
                    String msg = jsonObject.getString("msg");
                    if(0==ret)
                        return ret;
                    else if(ret == BHConstant.TOKEN_TIMEOUT)
                    {
                        bhAccesssToken.refreshToken(BHConstant.CLIENTID);
                        //update(clientID, activity);
                        throw new Exception(msg);
                    }
                    else
                    {
                        throw new Exception(msg);
                    }
                }

            }
            return ret;
    }

    /**
     * 活动查询
     * 查询志愿者平台上所有项目
     * 
     * @param activityName
     * @param activityLocation
     * @param groupCode
     * @return
     */
    public List<Activity> search(String activityName,String activityLocation,String groupCode,String pageIdx)throws Exception
    {
            List<Activity> acts = null;
            Map<String,String> map = new HashMap<String,String>();
            map.put("activityName",activityName);
            map.put("activityLocation",activityLocation);
            map.put("groupCode",groupCode);
            String postUrl = BHConstant.checkNetWork()+"/api/v1/activity/search?client="+ BHConstant.CLIENTID
                    + "&token=" + bhAccesssToken.getAccessToken(BHConstant.CLIENTID);
            String postEntity =  JSON.toJSONString(map,filter);
            String result = HttpsUtil.post(postUrl, postEntity);
            if(result != null && !result.trim().equals(""))
            {
                JSONObject jsonObject = JSONObject.parseObject(result);
                if(jsonObject != null)
                {
                    int res_code = jsonObject.getInteger("ret");
                    String msg = jsonObject.getString("msg");
                    if(res_code == 0)
                    {
                        acts = new ArrayList<Activity>();
                        JSONArray jsonArray = jsonObject.getJSONArray("result");
                        if(null == jsonArray || jsonArray.size() == 0)
                            return null;
                        for(int i=0;i<jsonArray.size();i++)
                        {
                            JSONObject object = jsonArray.getJSONObject(i);
                            //"activityName":"活动名称",
                            //"activitySummary":"简单介绍",
                            //"activityPostImgSmall":"http://www.site.com/pic.jpg",
                            //"activityLocation":"佛山",
                            //"activityStartPeriod":"2015-04-23 12:00:00",
                            //"activityEndPeriod":"2015-04-23 12:00:00",
                            //"activityDetailUrl":"http://test.com/detail.html",
                            //"activityRegStartPeriod":"2015-04-23 12:00:00",
                            //"activityRegEndPeriod":"2015-04-23 12:00:00",
                            //"activityCatalog":null,
                            //"groupCode":"546945788006",
                            //"groupName":"某某志愿者团体"
                            String activityCode = null;
                            activityName = object.getString("activityName");
                            String activitySummary = object.getString("activitySummary");
                            String activityPostImgSmall = object.getString("activityPostImgSmall");
                            activityLocation = object.getString("activityLocation");
                            String activityStartPeriod = object.getString("activityStartPeriod");
                            String activityEndPeriod = object.getString("activityEndPeriod");
                            String activityDetailUrl = object.getString("activityDetailUrl");
                            String activityRegStartPeriod = object.getString("activityRegStartPeriod");
                            String activityRegEndPeriod = object.getString("activityRegEndPeriod");
                            String activityCatalog = object.getString("activityCatalog");
                            groupCode = object.getString("groupCode");
                            String groupName = object.getString("groupName");
                            String activityScore = "0";//object.getString("activityScore");
                            BHActivity bhActivity = new BHActivity(activityCode,activityCatalog, activityDetailUrl, activityEndPeriod,
                                    activityLocation, activityName, activityPostImgSmall, activityRegEndPeriod,
                                    activityRegStartPeriod, activityStartPeriod, activitySummary, groupCode,groupName,activityScore);
                            acts.add(BHActivity.bhact2nativeact(bhActivity));

                        }
                    }
                    else if(res_code == BHConstant.TOKEN_TIMEOUT)
                    {
                        bhAccesssToken.refreshToken(BHConstant.CLIENTID);
                        //search(clientID, activityName, activityLocation, groupCode);
                        throw new Exception(msg);
                    }
                    else
                    {
                        throw new Exception(msg);
                    }
                }
            }
            return acts;
    }

    /**
     * 活动报名
     * 用户在第三方平台注册该平台发布项目活动后通过该接口把数据同步到志愿者管理信息平台
     * 
     * @param activityCode
     * @param volunteerCode
     * @param regStatus
     * @param regTime
     * @return
     */
    public int reg(String activityCode,String volunteerCode,String regStatus,String regTime)throws Exception
    {
            int regId = 0;
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd HHmmss");
            Map<String,String> map = new HashMap<String, String>();
            map.put("activityCode",activityCode);
            map.put("volunteerCode",volunteerCode);
            map.put("regStatus",regStatus);
            map.put("regTime",sdf2.format(sdf1.parse(regTime)));

            String postUrl = BHConstant.checkNetWork()+"/api/v1/activity/reg?client="+ BHConstant.CLIENTID
                    + "&token=" + bhAccesssToken.getAccessToken(BHConstant.CLIENTID);
            String postEntity =  JSON.toJSONString(map,filter);
            String result = HttpsUtil.post(postUrl, postEntity);
            if(result != null && !result.trim().equals(""))
            {
                JSONObject jsonObject = JSON.parseObject(result);
                if(jsonObject != null)
                {
                    int res_code = jsonObject.getInteger("ret");
                    String msg = jsonObject.getString("msg");
                    if(res_code == 0)
                    {
                        regId = jsonObject.getJSONObject("result").getIntValue("regId");
                    }
                    else if(res_code == BHConstant.TOKEN_TIMEOUT)
                    {
                        bhAccesssToken.refreshToken(BHConstant.CLIENTID);
                        //reg(clientID, activityCode, volunteerCode, regStatus, regTime);
                        throw new Exception(msg);
                    }
                    else
                    {
                        throw new Exception(msg);
                    }
                }
            }
            return regId;
    }

    /**
     * 活动签到
     * 用户在第三方平台签到该平台发布项目活动后通过该接口把数据同步到志愿者管理信息平台
     * 
     * @param activityCode
     * @param volunteerCode
     * @param signType
     * @param signTime
     * @param signLongitude
     * @param signDimensions
     * @return
     */
    public int sign(String activityCode,String volunteerCode,String signType,String signTime,String signLongitude,String signDimensions)throws Exception
    {
            int signId = 0;
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd HHmmss");
            Map<String,String> map = new HashMap<String, String>();
            map.put("activityCode",activityCode);
            map.put("volunteerCode",volunteerCode);
            map.put("signType",signType);
            map.put("signTime",sdf2.format(sdf1.parse(signTime)));
            map.put("signLongitude",signLongitude);
            map.put("signDimensions",signDimensions);

            String postUrl = BHConstant.checkNetWork()+"/api/v1/activity/sign?client="+ BHConstant.CLIENTID
                    + "&token=" + bhAccesssToken.getAccessToken(BHConstant.CLIENTID);
            String postEntity = JSON.toJSONString(map,filter);
            String result = HttpsUtil.post(postUrl, postEntity);
            if(result != null && !result.trim().equals(""))
            {
                JSONObject jsonObject = JSON.parseObject(result);
                if(jsonObject != null)
                {
                    int res_code = jsonObject.getInteger("ret");
                    String msg = jsonObject.getString("msg");
                    if(res_code == 0)
                    {
                        signId = jsonObject.getJSONObject("result").getInteger("signId");
                    }
                    else if(res_code == BHConstant.TOKEN_TIMEOUT)
                    {
                        bhAccesssToken.refreshToken(BHConstant.CLIENTID);
                        throw new Exception(msg);
                    }
                    else
                    {
                        throw new Exception(msg);
                    }
                }
            }
            return signId;
    }

    /**
     * 活动记录
     * 用户在第三方平台活动后获取到的积分和服务时间通过该接口把数据同步到志愿者管理信息平台
     * 
     * @param activityCode
     * @param volunteerCode
     * @param serviceHours
     * @param serviceScore
     * @return
     */
    public int record(String activityCode,String volunteerCode,String serviceHours,String serviceScore)throws Exception
    {
            int recordId = 0;
            Map<String,String> map = new HashMap<String, String>();
            map.put("activityCode",activityCode);
            map.put("volunteerCode",volunteerCode);
            map.put("serviceScore",serviceScore);
            //将分钟转化为小时
            DecimalFormat df  = new DecimalFormat("0.00");//这样为保持2位
            double hour = Double.parseDouble(serviceHours)/60D;
            //System.out.println(df.format(hour));
            map.put("serviceHours",String.valueOf(df.format(hour)));

            String postUrl = BHConstant.checkNetWork()+"/api/v1/activity/record?client=" + BHConstant.CLIENTID
                    + "&token=" + bhAccesssToken.getAccessToken(BHConstant.CLIENTID);
            String postEntity = JSON.toJSONString(map,filter);
            String result = HttpsUtil.post(postUrl, postEntity);
            if(result != null && !result.trim().equals(""))
            {
                JSONObject jsonObject = JSON.parseObject(result);
                if(jsonObject != null)
                {
                    int res_code = jsonObject.getInteger("ret");
                    String msg = jsonObject.getString("msg");
                    if(res_code == 0)
                    {
                        recordId = jsonObject.getJSONObject("result").getInteger("recordId");
                    }
                    else if(res_code == BHConstant.TOKEN_TIMEOUT)
                    {
                        bhAccesssToken.refreshToken(BHConstant.CLIENTID);
                        //record(clientID,activityCode,volunteerCode,serviceHours,serviceScore);
                        throw new Exception(msg);
                    }
                    else
                    {
                        throw new Exception(msg);
                    }
                }
            }
            return recordId;
    }

    /**
     * 志愿记录
     * 
     * @param volunteerCode
     * @return
     * @throws Exception
     */
    public Map<String,Object> record4UnregList(String volunteerCode,String pageIdx)throws Exception
    {
        Map<String,Object> resultMap = null;
        List<BHRecord> list = null;
        Map<String,String> map = new HashMap<String, String>();
        map.put("volunteerCode",volunteerCode);
        map.put("pageIdx",pageIdx);
        map.put("pageSize",pageSize);

        String postUrl = BHConstant.checkNetWork()+"/api/v1/activity/record4UnregPageList?client=" + BHConstant.CLIENTID
                +"&token=" + bhAccesssToken.getAccessToken(BHConstant.CLIENTID);
        String postEntity = JSON.toJSONString(map,filter);
        String result = HttpsUtil.post(postUrl, postEntity);

        if(result != null && !result.trim().equals(""))
        {


            JSONObject jsonObject = JSON.parseObject(result);
            if(jsonObject != null)
            {
                int res_code = jsonObject.getInteger("ret");
                String msg = jsonObject.getString("msg");
                if(0==res_code)
                {
                    resultMap = new HashMap<String, Object>();
                    jsonObject = jsonObject.getJSONObject("result");
                    int total = jsonObject.getInteger("total");
                    int totalPage = jsonObject.getInteger("totalPage");

                    JSONArray jsonArray = jsonObject.getJSONArray("result");
                    if(null != jsonArray && jsonArray.size()>0)
                    {
                        jsonObject = jsonArray.getJSONObject(0);
                        String totalServiceHours = jsonObject.getString("totalServiceHours");
                        String totalServiceScore = jsonObject.getString("totalServiceScore");
                        String initServiceHours = jsonObject.getString("initServiceHours");
                        resultMap.put("totalServiceHours",totalServiceHours);
                        resultMap.put("totalServiceScore",totalServiceScore);
                        resultMap.put("initServiceHours",initServiceHours);

                        JSONArray array = jsonObject.getJSONArray("recordList");
                        if(null == array || array.size() == 0)
                        {
                            resultMap.put("recordList",list);
                            return resultMap;
                        }

                        list = new ArrayList<BHRecord>();
                        for(int i=0;i<array.size();i++)
                        {
                            BHRecord record = JSON.toJavaObject(array.getJSONObject(i),BHRecord.class);
                            if(StringUtils.isNotEmpty(record.getRecordId()))
                                list.add(record);
                        }
                        if(totalPage ==Integer.parseInt(pageIdx))
                        {
                            if(StringUtils.isNotEmpty(initServiceHours) && Float.parseFloat(initServiceHours)>0)
                            {
                                //BHRecord record = new BHRecord("-99","0",initServiceHours,"注册服务时长",",");
                                //    list.add(record);
                            }
                        }
                        resultMap.put("recordList",list);
                    }
                }
                else if(res_code == BHConstant.TOKEN_TIMEOUT)
                {
                    bhAccesssToken.refreshToken(BHConstant.CLIENTID);
                    throw new Exception(msg);
                }
                else
                {
                    throw new Exception(msg);
                }
            }
        }
        return resultMap;
    }

    /**
     * 积分记录
     * 
     * @param volunteerCode
     * @return
     * @throws Exception
     */
    public Map<String,Object> integralRecrod(String token,String volunteerCode,String pageIdx)throws Exception
    {
        Map<String,Object> resultMap = null;
        List<BHRecord> list = null;
        Map<String,String> map = new HashMap<String, String>();
        map.put("volunteerCode",volunteerCode);
        map.put("pageIdx",pageIdx);
        map.put("pageSize",pageSize);

//        String postUrl = BHConstant.checkNetWork()+"/api/v1/activity/record4UnregPageList?client=" + DKQConstant.CLIENTID
//                +"&token=" + bhAccesssToken.getAccessToken(DKQConstant.CLIENTID);
        String postUrl = BHConstant.checkNetWork()+"/api/v1/activity/record4UnregPageList?client=" + BHConstant.CLIENTID
                +"&token=" + token;
        String postEntity = JSON.toJSONString(map,filter);
        String result = HttpsUtil.post(postUrl, postEntity);

        if(result != null && !result.trim().equals(""))
        {


            JSONObject jsonObject = JSON.parseObject(result);
            if(jsonObject != null)
            {
                int res_code = jsonObject.getInteger("ret");
                String msg = jsonObject.getString("msg");
                if(0==res_code)
                {
                    resultMap = new HashMap<String, Object>();
                    jsonObject = jsonObject.getJSONObject("result");
                    int total = jsonObject.getInteger("total");
                    int totalPage = jsonObject.getInteger("totalPage");

                    JSONArray jsonArray = jsonObject.getJSONArray("result");
                    if(null != jsonArray && jsonArray.size()>0)
                    {
                        jsonObject = jsonArray.getJSONObject(0);
                        String totalServiceHours = jsonObject.getString("totalServiceHours");
                        String totalServiceScore = jsonObject.getString("totalServiceScore");
                        resultMap.put("totalServiceHours",totalServiceHours);
                        resultMap.put("totalServiceScore",totalServiceScore);

                        JSONArray array = jsonObject.getJSONArray("recordList");
                        if(null == array || array.size() == 0)
                        {
                            resultMap.put("recordList",list);
                            return resultMap;
                        }

                        list = new ArrayList<BHRecord>();
                        for(int i=0;i<array.size();i++)
                        {
                            BHRecord record = JSON.toJavaObject(array.getJSONObject(i),BHRecord.class);
                            if(!record.getServiceScore().equals("0.00") && (Integer.parseInt(record.getServiceScore()) >0) && StringUtils.isNotEmpty(record.getRecordId()))
                                list.add(record);
                        }
                        resultMap.put("recordList",list);
                    }

                }
                else if(res_code == BHConstant.TOKEN_TIMEOUT)
                {
                    bhAccesssToken.refreshToken(BHConstant.CLIENTID);
                    throw new Exception(msg);
                }
                else
                {
                    throw new Exception(msg);
                }
            }
        }
        return resultMap;
    }
}
